<template>
  <div class="login-container">
    <div class="login-left">
    </div>
    <div class="login-right">
      <div class="login-form">
        <h2 class="welcome">重置密码</h2>
        <p class="sub-title">智慧学习考核系统</p>

        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="form">
          <el-form-item prop="phone">
            <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model="loginForm.code" placeholder="请输入验证码">
              <template #append>
                <span class="text-custom-blue cursor-pointer" :class="{ 'text-gray-400': isCountDown }"
                  @click="handleGetCode">
                  {{ codeText }}
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item prop="passwords">
            <el-input v-model="loginForm.passwords" type="password" placeholder="请确认密码" />
          </el-form-item>
          <el-button type="primary" class="login-button" :loading="loading" @click="handleReset">
            提交
          </el-button>

          <div class="flex justify-between align-center">
            <span class="text-custom-blue cursor-pointer" @click="goToRegister">去注册!</span>
            <span class="text-custom-blue cursor-pointer" @click="goToLogin">去登录!</span>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/index.js'
import { validatePassword } from '@/utils/common.js'
import { Encrypt } from '@/utils/encryption.js'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  phone: '',
  password: '',
  passwords: '',
  code: '',
  remember: false
})

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== loginForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, message: '验证码不能少于6位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  passwords: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
}

watch(
  () => loginForm.password,
  () => {
    if (loginForm.passwords) {
      loginFormRef.value?.validateField('passwords')
    }
  }
)

const handleReset = () => {
  if (!loginFormRef.value) return
  loginFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true

      userApi.forgetPassword({
        mobile: loginForm.phone,
        code: loginForm.code,
        password: Encrypt(loginForm.password),
        password_again: Encrypt(loginForm.passwords),
      }).then(res => {
        ElMessage.success('密码重置成功')
        router.push('/login')
      })
    }
    loading.value = false;
  })
}

const goToRegister = () => {
  router.push('/register')
}
const goToLogin = () => {
  router.push('/login')
}

// 添加验证码相关响应式变量
const isCountDown = ref(false)
const countdown = ref(60)
const codeText = ref('获取验证码')

// 获取验证码
const handleGetCode = async () => {
  if (isCountDown.value) return
  if (!loginForm.phone) {
    ElMessage.warning('请输入手机号')
    return
  } else {
    // 开始倒计时
    isCountDown.value = true
    codeText.value = `${countdown.value}s`

    const timer = setInterval(() => {
      countdown.value--
      codeText.value = `${countdown.value}s`

      if (countdown.value <= 0) {
        clearInterval(timer)
        isCountDown.value = false
        codeText.value = '获取验证码'
        countdown.value = 60
      }
    }, 1000)

    // 这里添加获取验证码的API调用
    const res = await userApi.sms({
      mobile: loginForm.phone,
      sms_type: 'pass'
    })
    ElMessage.success('验证码已发送')
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  background: #fff;
  padding: 8px;

  .login-left {
    flex: 3;
    padding: 40px;
    background-image: url('@/assets/images/login-bg.png');
    background-size: cover;
    position: relative;

    .logo-title {
      display: flex;
      align-items: center;
      gap: 12px;

      .logo {
        width: 40px;
        height: 40px;
      }

      span {
        font-size: 24px;
        font-weight: 500;
        color: #1890FF;
      }
    }

    .login-bg {
      width: 80%;
      max-width: 600px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  .login-right {
    flex: 2;
    // width: 500px;
    display: flex;
    align-items: center;
    justify-content: center;

    .login-form {
      width: 360px;

      .welcome {
        font-family: MiSans, MiSans;
        font-weight: 600;
        font-size: 36px;
        color: rgba(0, 0, 0, 0.88);
        line-height: 44px;
        letter-spacing: 7px;
        text-align: center;
        font-style: normal;
        text-transform: none;
        margin-bottom: 8px;
      }

      .sub-title {
        font-family: MiSans, MiSans;
        font-weight: 500;
        font-size: 24px;
        color: rgba(0, 0, 0, 0.65);
        line-height: 32px;
        letter-spacing: 6px;
        text-align: center;
        font-style: normal;
        text-transform: none;
        margin-bottom: 40px;
      }

      .form {
        .el-input {
          height: 40px;

          :deep(.el-input__inner) {
            height: 40px;
          }
        }

        .remember-forgot {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin: 16px 0 24px;

          .el-checkbox {
            color: #4E5969;
          }
        }

        .login-button {
          width: 100%;
          height: 40px;
          font-size: 16px;
          margin-bottom: 16px;
        }

        .register {
          font-family: MiSans, MiSans;
          font-weight: 400;
          font-size: 14px;
          display: flex;

          :deep(.el-link__inner) {
            color: rgba(0, 0, 0, 0.65) !important;
            line-height: 22px;
            font-style: normal;
            text-transform: none;
          }

        }
      }
    }
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .login-container {
    .login-left {
      display: none;
    }

    .login-right {
      width: 100%;
      padding: 20px;

      .login-form {
        width: 100%;
      }
    }
  }
}

.text-gray-400 {
  color: #9ca3af !important;
  cursor: not-allowed;
}
</style>
